package com.zdyt.opc.service.impl;

import com.zdyt.opc.common.DataSampAndSender;
import com.zdyt.opc.config.OpcOperation;
import com.zdyt.opc.config.RestTemplateProperties;
import com.zdyt.opc.entity.Item;
import com.zdyt.opc.entity.ItemTask;
import com.zdyt.opc.entity.SampAccessTask;
import com.zdyt.opc.service.OpcCollectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.Map;

@Service
public class OpcCollectServiceImpl implements OpcCollectService {

    @Autowired
    OpcOperation opcOperation;

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    RestTemplateProperties restTemplateProperties;


    @Override
    public List<Item> getAllItems() {
        return opcOperation.getAllItemList();
    }

    @Override
    public SampAccessTask addSampTask(String taskName,Integer period,String targetUrl) {
        return opcOperation.createSampAccessTask(taskName,period,targetUrl);
    }

    @Override
    public List<SampAccessTask> getAllSampTasks(String progId) {
        return opcOperation.getTagertServerAccessTasks(progId);
    }

    @Override
    public SampAccessTask addItemToTask(ItemTask itemTask) {
        List<String> itemIds = itemTask.getItemIds();
        Integer taskId = itemTask.getTaskId();
        String title = itemTask.getTitle();
        Map<String, String> itemId2CN = itemTask.getItemId2CN();

        // 构造数据采集发送器
        // 数据发送 目标url
        SampAccessTask task = opcOperation.getAccessTaskById(taskId);
        if (task == null){
            throw new RuntimeException("目标任务不存在！");
        }
        DataSampAndSender sender = new DataSampAndSender(restTemplate,task.getTargetUrl(), itemId2CN, title);

        return opcOperation.addSampPointToTask(itemIds,taskId,sender);
    }

    @Override
    public SampAccessTask startSampTask(Integer taskId) {
        return opcOperation.startSampAccessTaskById(taskId);
    }

    @Override
    public SampAccessTask getTaskById(Integer taskId) {
        return opcOperation.getAccessTaskById(taskId);
    }

    @Override
    public SampAccessTask stopSampTask(Integer taskId) {
        return opcOperation.stopSampAccessTaskById(taskId);
    }

    @Override
    public void deleteSampTaskById(Integer taskId) {
        opcOperation.deleteSampAccessTaskById(taskId);
    }

    @Override
    public void deleteSampItemFromTask(ItemTask itemTask) {
        Integer taskId = itemTask.getTaskId();
        List<String> itemIds = itemTask.getItemIds();
        opcOperation.deleteSampItemFromTask(itemIds,taskId);
    }

}
